<?php
$dir = dirname(__FILE__);                 //查找当前脚本所在路径
require $dir ."/function.php";
require $dir . "/db_config.php";         //引入数据库连接类
require $dir . "/Pdo.class.php";
require $dir . "/PHPExcel/PHPExcel.php"; //引入phpexcel类

//查询数据


/**一、实例化类phpexcel类**/
$objPHPExcel = new PHPExcel();
//获取分类数据
$cate = M($phpexcel)->q("SELECT count(*) count FROM tj_giftcate");
for($i=1;$i<$cate[0]['count'];$i++){
    if($i>1){
        //创建内置表
        $objPHPExcel->createSheet();
    }
    //把新创建的sheet设定为当前的活动sheet
    $objPHPExcel->setActiveSheetIndex($i-1);
    //获取当前活动sheet
    $objSheet = $objPHPExcel->getActiveSheet();
    //为当前sheet取名
    $objSheet->setTitle("分类-" . $i);
    //设置标题
    $objSheet->setCellValue("A1","分类名称")->setCellValue("B1","商品名称")->setCellValue("C1","商品标题")->setCellValue("D1","商品描述")->setCellValue("E1","商品积分");
    //查询关联数据
    $sql = "SELECT a.*,b.name catename FROM tj_gift a JOIN tj_giftcate b ON a.sub = b.id WHERE a.sub = " .$i ;
    $giftData = M($phpexcel)->q($sql);
    //填充数据
    $j = 2;
    foreach($giftData as $k=>$v){
        $objSheet->setCellValue("A".$j,$v['catename'])
                 ->setCellValue("B".$j,$v['name'])
                 ->setCellValue("C".$j,$v['title'])
                 ->setCellValue("D".$j,$v['description'])
                 ->setCellValue("E".$j,$v['points']);
        $j++;
    }
}
/**生成excel文件**/
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
/**保存文件**/
//$objWriter->save($dir . "/excel.xls");

/**输出到浏览器**/
browser_export('Excel5', 'browser_excel03.xls');
$objWriter->save('php://output');

function browser_export($type, $filename)
{

    if ($type == "Excel5") {
        //告诉浏览器将要输出excel03文件
        header('Content-Type: application/vnd.ms-excel');
    } else {
        //告诉浏览器输出excel07文件
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    }
    //告诉浏览器将要输出文件的名字
    header('Content-Disposition: attachment;filename=' . $filename);
    //禁止缓存
    header('Cache-Control: max-age=0');
}
